<template>
	<view class="page-view">
		<view class="filter-pane">
			<u-navbar :border-bottom="false">
				<!-- <u-icon size="32" class="u-m-r-18" name="arrow-left" @click="$u.route({type:'back'})"></u-icon> -->
				<view class="nav-view">
					<bb-search :city="city" @toLocation="toLocation" background-color="#F6F6F6" placeholder="可直接搜索要找的把关师、能人"
						:showBtn="false" @seachTap="$u.route('/pages/subpage/search/index',{type:1})"></bb-search>
				</view>
			</u-navbar>
			<bb-tabs :list="tabList" :current="current" @change="tabchange"></bb-tabs>
			<view class="u-flex u-relative">
				<u-dropdown class="u-dropdown" ref="uDropdown" menu-icon="arrow-down-fill" :active-color="config.mainColor"
					menu-icon-size="24">
					<u-dropdown-item title="综合">
						<view class="slot-content">
							<view class="item-box placeholder">
								<view class="item" :class="[orderBy==item.value?'active':'']" v-for="(item,index) in options1"
									:key="index" @tap="tagClick(item.value)">{{item.label}}
								</view>
							</view>
							<view class="u-flex">
								<u-button type="default" size="medium"
									:customStyle="{borderColor: '#cccccc',color: '#999999', width:'227rpx'}" plain hover-class="none"
									shape="circle" @click="resetSort()">重置</u-button>
								<view class="u-flex-1 u-m-l-24">
									<u-button type="primary" size="medium" :customStyle="{ width:'100%'}" hover-class="none"
										shape="circle" @click="refirshData()">确定</u-button>
								</view>
							</view>
						</view>
					</u-dropdown-item>
					<u-dropdown-item title="服务方式" :options="options2">
						<view class="slot-content">
							<view class="item-box ">
								<view class="item" :class="[filter===item.value?'active':'']" v-for="(item,index) in options2"
									:key="index" @tap="filter=item.value">{{item.label}}
								</view>
							</view>
							<view class="u-flex">
								<u-button type="default" size="medium"
									:customStyle="{borderColor: '#cccccc',color: '#999999', width:'227rpx'}" plain hover-class="none"
									shape="circle" @click="resetSort()">重置</u-button>
								<view class="u-flex-1 u-m-l-24">
									<u-button type="primary" size="medium" :customStyle="{ width:'100%'}" hover-class="none"
										shape="circle" @click="refirshData()">确定</u-button>
								</view>
							</view>
						</view>
					</u-dropdown-item>
				</u-dropdown>
				<view class="switch-map" @click="switchMapHandle">
					<view class="u-flex switch-item u-col-center">
						<view class="u-flex-1 align-center" :class="showMap?'white':''">地图</view>
						<view class="u-flex-1 align-center" :class="!showMap?'white':''">列表</view>
					</view>
					<view class="item-bg" :class="showMap?'left':'right'"></view>
				</view>
			</view>
		</view>

		<view class="content-list">
			<mescroll-uni @init="mescrollInit" @down="downCallback" @up="upCallback" :fixed="false" v-show="!showMap"
				:up="upOption" @emptyclick="toApply">
				<view class="u-p-30">
					<view class="" v-for="(item,index) in powerList" :key="index">
						<bb-member :info="item"></bb-member>
					</view>
				</view>
			</mescroll-uni>
			<view class="map-view" v-show="showMap">
				<!-- #ifdef MP -->
				<map id="MapView" ref="MapView" style="width: 750rpx;height: 1400rpx;" show-compass show-location
					enable-building :scale="scale" enable-3D :latitude="Number(currentGPS[1])" :longitude="Number(currentGPS[0])"
					:markers="markers" @callouttap="markerTapHandle" @tap="mapTapHandle">
					<cover-view slot="callout">
						<block v-for="(item, index) in markers" :key="index">
							<cover-view :marker-id="item.id" style="width:60rpx;height: 70rpx;">
								<cover-image style="width: 60rpx;height: 70rpx;" src="/static/dibiao.png"></cover-image>
								<cover-image style="width: 56rpx;height: 56rpx;margin-top: -68rpx;margin-left: 2rpx;border-radius: 50%;"
									:src="item.customCallout.avatar" @load="imageLoad(index)" v-show="item.show"></cover-image>
							</cover-view>
						</block>
					</cover-view>

					<cover-view class="current-location" @click="resetView">
						<cover-image src="/static/location.png" class="icon"></cover-image>
					</cover-view>
				</map>
				<!-- #endif -->
				<!-- #ifdef APP || H5 -->
				<view id='amap' :style="mapStyle">
				</view>
				<cover-image :markers="markers" :location="currentGPS" :change:location="aMapRenderJs.getLocation"
					:change:markers="aMapRenderJs.getmarkers"></cover-image>
				<!-- #endif -->
				<view class="select-power" v-if="seletMarkPower.uid">
					<bb-member :info="seletMarkPower"></bb-member>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import config from '@/config.js'
	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				tabList: [],
				showMap: false,
				config: this.$appConfig,
				options1: [{
						label: '不限',
						value: '',
					},
					{
						label: '评分',
						value: 'score',
					},
					{
						label: '发布时间',
						value: 'time',
					},
					{
						label: '价格',
						value: 'price',
					},
					{
						label: '距离',
						value: 'location',
					}
				],
				options2: [{
						label: '不限',
						value: '',
					}, {
						label: '预约帮',
						value: 0,
					},
					{
						label: '及时帮',
						value: 1,
					},
				],
				current: 0,
				city: this.$store.state.vuex_address.city || config.D_CITY,
				location: this.$store.state.vuex_address.location || config.D_LOC,
				orderBy: '',
				filter: '',
				parentId: 0,
				classId: '',
				powerList: [],
				markers: [],
				scale: 12,
				mapContext: null,
				currentGPS: [],
				seletMarkPower: {},
				mapStyle: {
					width: '750rpx',
					height: '780px'
				},
				upOption: {
					empty: {
						use: true,
						tip: "暂时没有相关把关师认证哦~",
						btnText: '我要认证'
					}
				}
			}
		},
		onShow() {
			uni.$off('selectLocation')
		},
		onLoad(e) {
			this.parentId = e.id || 0;
			this.queryClassTabs();
			this.currentGPS = this.location.split(',')
		},
		onReady() {
			// #ifdef MP
			this.mapContext = uni.createMapContext('MapView', this);
			this.mapContext.setCenterOffset({
				offset: [0.5, 0.4]
			})
			// #endif
		},
		mounted() {
			setTimeout(() => {
				this.listContentRect()
			}, 300)
		},
		methods: {
			listContentRect() {
				const query = uni.createSelectorQuery().in(this);
				query
					.select(".content-list")
					.boundingClientRect((data) => {
						const systemInfo = this.$store.state.vuex_sysmbelInfo;
						let tabBarHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom;; // TabBar的高度
						// #ifdef H5
						tabBarHeight = 50
						// #endif
						this.mapStyle.height = (data.height - tabBarHeight) + 'px';
					})
					.exec();
			},
			switchMapHandle() {
				this.showMap = !this.showMap
				if (this.showMap && this.markers.length == 0) {
					this.getALlMarkers()
				}
			},
			// 去认证
			toApply() {
				this.$u.route('/pages/subpage/profile/attestation')
			},
			imageLoad(index) {
				setTimeout(() => {
					this.$set(this.markers[index], 'show', true)
					this.markers[index].show = true
				}, 10)
			},
			// 复位地图
			resetView() {
				this.seletMarkPower = {}
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						const {
							latitude,
							longitude
						} = res;
						this.mapContext.moveToLocation({
							latitude,
							longitude
						})
					}
				})
			},
			// 点击marker
			markerTapHandle(e) {
				this.seletMarkPower = {}
				setTimeout(() => {
					const {
						markerId
					} = e.detail;
					const powerItem = this.markers.find(item => item.id == markerId);
					this.seletMarkPower = powerItem.customCallout.info;
				}, 300)

			},
			// 点击地图
			mapTapHandle() {
				this.seletMarkPower = {}
			},
			upCallback(page) {
				this.tabList.length > 0 && this.queryPowerList(page)
			},
			refirshData() {
				this.mescroll.resetUpScroll();
				this.$refs.uDropdown.close();
			},
			tabchange(index) {
				this.current = index;
				this.classId = this.tabList[index].id;
				this.refirshData()
				if (this.showMap) {
					this.markers = []
					this.getALlMarkers()
				}
			},
			toLocation() {
				uni.$on('selectLocation', (data) => {
					console.log(data);
					const {
						city,
						location
					} = data
					this.city = city
					this.location = location
					this.refirshData()
				})
				this.$u.route('/pages/subpage/list/location')
			},
			tagClick(value) {
				this.orderBy = value
			},
			resetSort() {
				this.orderBy = ''
				this.filter = ''
				this.refirshData()
			},
			async queryClassTabs() {
				this.tabList = [];
				const tabList = await this.$u.api.public.industry_class({
					pid: this.parentId,
					type: 'serve'
				});
				this.tabList = [{
					name: '全部',
					id: this.parentId
				}, ...tabList]
				this.classId = this.tabList[0].id
				this.refirshData()
			},
			queryPowerList(page) {
				this.$u.api.public.power_lst({
					keyword: '',
					location: this.location,
					order: this.orderBy,
					freeType: this.filter,
					page: page.num,
					limit: page.size,
					class_id: this.classId
				}).then(res => {
					this.powerList = page.num == 1 ? res : [...this.powerList, ...res];
					this.mescroll.endSuccess(res.length, res.length >= page.size);
				})
			},
			getALlMarkers(num = 1, size = 10) {
				this.$u.api.public.power_lst({
					keyword: '',
					location: this.location,
					order: this.orderBy,
					freeType: this.filter,
					page: num,
					limit: size,
					class_id: this.classId
				}).then(res => {
					const markers = res.map(item => {
						return {
							id: item.uid,
							title: item.name,
							width: 1,
							height: 1,
							latitude: Number(item.lat),
							longitude: Number(item.lng),
							iconPath: '/static/1.png',
							show: false,
							customCallout: {
								display: "ALWAYS",
								avatar: item.avatar,
								info: item
							}
						};
					})
					this.markers = num == 1 ? markers : [...this.markers, ...markers];
					if (markers.length >= size) {
						num++;
						this.getALlMarkers(num)
					}
				})
			}
		}
	}
</script>
<!-- #ifndef MP -->
<!-- 高德地图 web api -->
<!-- 地图引入高德 使用renderjs 引入 对renderjs不了解 可以看着案例去弄 -->
<script module="aMapRenderJs" lang="renderjs">
	const A_MAP_KEY = "dc9679975db6077a9e49b5e4b11a7867"; // 地图key
	const A_MAP_SECRET_KEY = "63d08bb686f7e70f689f937e11bb6ae2"; // 地图密钥

	export default {
		data() {
			return {
				map: null,
				markersList: [],
				location: []
			}
		},
		mounted() {
			this.getmarkers()
			// 地图初始化 
			if (typeof window.AMap === 'function') {
				this.initAmap();
			} else {
				window._AMapSecurityConfig = {
					securityJsCode: A_MAP_SECRET_KEY,
				};
				const script = document.createElement('script');
				script.src = `https://webapi.amap.com/maps?v=2.0&key=${A_MAP_KEY}&plugin=AMap.Walking`;
				script.onload = this.initAmap.bind(this);
				document.head.appendChild(script);
			}
		},
		methods: {
			// 获取 外卖员的数据
			getmarkers(e) {
				this.map && this.map.clearMap();

				if (e && e.length > 0) {
					this.markersList = e;
					this.drawMarks()
				}
			},
			getLocation(e) {
				if (e) {
					this.location = e.map(item => Number(item))
				}
			},
			// 初始化
			initAmap() {
				this.map = new AMap.Map('amap', {
					resizeEnable: true,
					zoom: 12,
					center: this.location, //初始化地图中心点位置
				})
				this.map.on('click', () => {
					this.$ownerInstance.callMethod('mapTapHandle')
				})
				AMap.plugin('AMap.Geolocation', () => {
					const geolocation = new AMap.Geolocation({
						enableHighAccuracy: true, //是否使用高精度定位，默认:true
						timeout: 10000, //超过10秒后停止定位，默认：5s
						position: 'RB', //定位按钮的停靠位置
						offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
						zoomToAccuracy: false, //定位成功后是否自动调整地图视野到定位点
						panToLocation: true
					});
					this.map.addControl(geolocation);
					geolocation.getCurrentPosition((status, result) => {
						this.$ownerInstance.callMethod('mapTapHandle')
						if (status == 'complete') {
							console.log(result);
						} else {
							console.log(result)
						}
					});
				})
			},
			drawMarks() {
				console.log('重回，', this.markersList.length);
				let that = this
				// 遍历 marker位置
				that.markersList.forEach(item => {
					const bgicon = new AMap.Icon({
						size: new AMap.Size(30, 35), // 图标尺寸
						image: "static/dibiao.png", // Icon的图像
						imageSize: new AMap.Size(30, 35) // 根据所设置的大小拉伸或压缩图片
					});
					const wmarkert = new AMap.Marker({
						icon: bgicon, // 自定义点标记覆盖物内容
						position: [item.longitude, item.latitude],
						anchor: "bottom-center",
						extData: {
							markerId: item.customCallout.info.uid
						}
					});
					that.map.add(wmarkert);
					const avatar = `<img class="map-avatar" src="${item.customCallout.avatar}"></img>`;
					const wmarker = new AMap.Marker({
						position: [item.longitude, item.latitude],
						offset: new AMap.Pixel(0, -3),
						content: avatar, // 添加 Icon 实例
						anchor: "bottom-center",
						extData: {
							markerId: item.customCallout.info.uid
						}
					});
					wmarker.on('click', (e) => {
						const extData = e.target.getExtData()
						that.$ownerInstance.callMethod('markerTapHandle', {
							detail: extData
						})
					})
					that.map.add(wmarker);
				})
			}
		}
	}
</script>
<style>
	.map-avatar {
		width: 26px;
		height: 26px;
		border-radius: 50%;
	}
</style>
<!-- #endif -->
<style scoped lang="scss">
	.page-view {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.filter-pane {
		width: 100%;
		background-color: #fff;
	}

	.content-list {
		flex: 1;
		min-height: 0;
		overflow: hidden;
	}

	.nav-view {
		/* #ifdef MP */
		width: 440rpx;
		/* #endif */

		/* #ifndef MP */
		padding-right: 30rpx;
		/* #endif */
	}

	.slot-content {
		background-color: #FFFFFF;
		padding: 30rpx;

		.item-box {
			margin-bottom: 60rpx;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			&.placeholder:after {
				content: '';
				display: block;
				width: 180rpx;
			}

			.item {
				color: $u-tips-color;
				width: 180rpx;
				height: 60rpx;
				background: #EFEFEF;
				border-radius: 80rpx 80rpx 80rpx 80rpx;
				line-height: 60rpx;
				text-align: center;
				margin-bottom: 30rpx;
			}

			.active {
				color: $u-type-primary;
				background-color: #E5FEEB;
			}
		}
	}

	.current-location {
		position: absolute;
		bottom: 250rpx;
		right: 30rpx;
		background-color: #fff;
		width: 80rpx;
		height: 80rpx;
		border-radius: 10rpx;
		box-shadow: 1px 1px 16rpx 0px rgba(0, 101, 77, 0.1);
		display: flex;
		align-items: center;
		justify-content: center;

		.icon {
			width: 60rpx;
			height: 60rpx;
		}
	}

	.select-power {
		position: fixed;
		left: 30rpx;
		right: 30rpx;
		bottom: 180rpx;
	}
</style>